/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package easybooking.clients.gui.editor;

import easybooking.EBInterface;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;

/**
 * The form used to display planes.
 * @author Tim Schröder
 * http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting
 */
public class PlaneForm extends JPanel {

    private EBInterface ebi;
    private JLabel lblSearch;
    private JTextField txfSearch;
    private JTable tblPlanes;
    private JPanel buttonPanel;
    private JButton btnCreatePlane;
    private JButton btnEditPlane;
    private JButton btnDeletePlane;
    private Vector tableData;
    private TableRowSorter<PlaneTableModel> sorter;
    private PlaneTableModel model;
    private JLabel lblLogo;
    private JButton btnRefresh;

    /**
     * Constructoor of the plane form
     * @param ebif an EBInterface object
     */
    public PlaneForm(EBInterface ebif) {
        ebi = ebif;
        //tableData = ebi.ebic.getAllTypess();
        //generateComponents();

    }

    /**
     * get the inserted text from the search text field
     * @return the searched text
     */
    public String getSearchText() {
        return txfSearch.getText();
    }

    /**
     * gets and returns the selected type from the table
     * @return the selected type
     */
    public Object getSelectedPlane() {
        if (tblPlanes.getSelectedRow() == -1) {
            // returns null if now row is selected
            return null;
        }
        // converts the selected row from the view to the corresponding model row
        int modelRow = tblPlanes.convertRowIndexToModel(tblPlanes.getSelectedRow());
        // gets the type object from the model, this is not good, think about it
        return tblPlanes.getModel().getValueAt(modelRow, 4);
    }

    /**
     * sets the data for the plane table model
     * @param p is the vector containing all planes and is used to create the table
     */
    public void setTableData(Vector p) {
        tableData = p;

    }

    /**
     * calls the generateComponents() method to create and show the PlaneForm
     */
    public void createAndShowForm() {
        generateComponents();

    }

    /**
     * Generates all components to create an display the GUI
     */
    private void generateComponents() {
        // sets system default look and feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception exc) {
            System.err.println("Error loading L&F: " + exc);
        }

        // Sets the border
        this.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Manage Planes"),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        this.setLayout(new GridBagLayout());
        GridBagLayout gbl = new GridBagLayout();



        lblSearch = new JLabel("Search:");
        // Places the GUI elements in the layout using addComponent                                  x, y, w, h, wx, wy
        addComponent(this, gbl, lblSearch, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0, 0, 1, 1, 0, 0);
        txfSearch = new JTextField(30);

        // registrates the document listener for filtering
        txfSearch.getDocument().addDocumentListener(
                new DocumentListener() {

                    public void changedUpdate(DocumentEvent e) {
                        typeFilter();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        typeFilter();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        typeFilter();
                    }
                });
        // Places the GUI elements in the layout using addComponent                                  x, y, w, h, wx, wy
        addComponent(this, gbl, txfSearch, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 0, 1, 1, 0, 0);

        btnRefresh = new JButton();
        btnRefresh.setName("refreshPlanes");
        btnRefresh.setActionCommand("refresh");
        btnRefresh.addActionListener(ebi);
        btnRefresh.setSize(new Dimension(16, 16));
        Icon refreshIcon = new ImageIcon(this.getClass().getResource("/easybooking/clients/gui/images/refresh.png"));
        btnRefresh.setIcon(refreshIcon);
        addComponent(this, gbl, btnRefresh, GridBagConstraints.NONE, GridBagConstraints.WEST, 2, 0, 1, 1, 0, 0);

        lblLogo = new JLabel();
        Icon Logo = new ImageIcon(this.getClass().getResource("/easybooking/clients/gui/images/easyBookingLogoSmall2.png"));
        lblLogo.setIcon(Logo);
        addComponent(this, gbl, lblLogo, GridBagConstraints.NONE, GridBagConstraints.EAST, 4, 0, 1, 1, 0, 0);



        // creates table with type model and data
        tblPlanes = new JTable();
        // gets an instance of the typeTableModel with table data 
        model = new PlaneTableModel(tableData, ebi.getInterfaceClient());

        // creates the sorter for the table depending on the table model
        sorter = new TableRowSorter<PlaneTableModel>(model);

        // sets the model of tblTypes
        tblPlanes.setModel(model);

        // adds the sorter to tblTypes
        tblPlanes.setRowSorter(sorter);

        // allows only a single selection on the table
        tblPlanes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);



        // adds the table within a scroll pane to the layout
        // Places the GUI elements in the layout using addComponent                                                x, y, w, h, wx, wy
        addComponent(this, gbl, new JScrollPane(tblPlanes), GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0, 1, 5, 1, 1, 1);


        // adds the buttton panel to the layout
        // Places the GUI elements in the layout using addComponent                                                 x, y, w, h, wx, wy
        addComponent(this, gbl, this.createButtonPanel(), GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0, 2, 5, 1, 0, 0);

    }

    /**
     * Creates a tablerowfilter for the PlaneTableModle based on ragular expressions and adds it to the sorter
     */
    private void typeFilter() {
        RowFilter<PlaneTableModel, Object> rf = null;
        //If current expression doesn't parse, don't update.
        try {
            //                                              columns included in filter
            rf = RowFilter.regexFilter(txfSearch.getText(), 0, 1, 2, 3, 4, 5);

        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rf);
    }

    /**
     * Creates all buttons to create, edit or delete a Plane
     * @return a JPanel with 3 buttons
     */
    private JPanel createButtonPanel() {

        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridBagLayout());
        GridBagLayout gbl = new GridBagLayout();

        btnCreatePlane = new JButton("Create Plane");
        Icon nCuIcon = new ImageIcon(PlaneForm.class.getResource("/easybooking/clients/gui/images/create.png"));
        btnCreatePlane.setIcon(nCuIcon);
        btnCreatePlane.setActionCommand("createPlane");
        btnCreatePlane.addActionListener(ebi);

        btnEditPlane = new JButton("Edit");
        Icon ediIcon = new ImageIcon(PlaneForm.class.getResource("/easybooking/clients/gui/images/edit.png"));
        btnEditPlane.setIcon(ediIcon);
        btnEditPlane.setActionCommand("editPlane");
        btnEditPlane.addActionListener(ebi);

        btnDeletePlane = new JButton("Delete");
        Icon delIcon = new ImageIcon(PlaneForm.class.getResource("/easybooking/clients/gui/images/trash.gif"));
        btnDeletePlane.setIcon(delIcon);
        btnDeletePlane.setActionCommand("deletePlane");
        btnDeletePlane.addActionListener(ebi);

        // Sets the buttons the same size
        btnEditPlane.setPreferredSize(btnDeletePlane.getPreferredSize());

        // Adds the buttons to the buttonPanel
        addComponent(buttonPanel, gbl, btnCreatePlane, GridBagConstraints.NONE, GridBagConstraints.WEST, 0, 0, 1, 1, 0, 0);
        addComponent(buttonPanel, gbl, btnEditPlane, GridBagConstraints.NONE, GridBagConstraints.EAST, 1, 0, 1, 1, 1, 0);
        addComponent(buttonPanel, gbl, btnDeletePlane, GridBagConstraints.NONE, GridBagConstraints.EAST, 2, 0, 1, 1, 0, 0);

//        buttonPanel.add(btnCreateType);
//        buttonPanel.add(btnEditType);
//        buttonPanel.add(btnDeleteType);
        return buttonPanel;
    }

    /**
     * defines the layout of the GUI
     * @param cont container to which the component is added
     * @param gbl GridBagLayout object
     * @param c compontent which is added to the container
     * @param fill how to use free space in the cell around the component
     * @param anchor where to fix an align the component
     * @param x x position in the grid layout
     * @param y y position in the grid layout
     * @param width number of columns the element should spread
     * @param hight number of rows the element should spread
     * @param weightx handels the horizontal free space
     * @param weighty handels the vertical free space
     */
    private static void addComponent(Container cont, GridBagLayout gbl, Component c, int fill, int anchor, int x, int y, int width, int hight, double weightx, double weighty) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = fill;
        gbc.anchor = anchor;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = hight;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbc.insets = new Insets(10, 10, 10, 10);
        //gbl.setConstraints(c, gbc);
        cont.add(c, gbc);


    }
}
